#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os, sys
import zipfile


def _exec_cmd(cmd):
    pipe = os.popen(cmd,"r")
    result = pipe.readlines()
    pipe.close()
    
    return result

def _split_input(fn_input, prefix, lines):
    fn_input = os.path.expanduser(fn_input)
   
    e_msg = 'Pls. check input file specified.'
    out_dir = os.path.dirname(fn_input)
    #
    if not prefix:
        prefix = 'slice_' + os.path.basename(fn_input).split('.')[0] + '_'
        
    print out_dir
    if not fn_input:
        print >> sys.stderr, e_msg
        sys.exit(1)
    else:
        try:
            in_fd = file(fn_input, 'r')
        except Exception, e:
            print >> sys.stderr, e_msg
            sys.exit(1)
        abs_lines = len(in_fd.readlines())
        in_fd.close()
        
        in_fd = file(fn_input, 'r')
        splits = (abs_lines / lines) + 1
        for i in range(0, splits):
            out_fn = os.path.join(out_dir, prefix + str(i) + '.data')
            out_fd = file(out_fn, 'w')
            for j in range(0, lines):
                ll = in_fd.readline() 
                # EOF
                if not ll:
                    break
                else:
                    out_fd.write(ll)
            out_fd.close()
        in_fd.close()

def _zip_exec(exec_dir, out_fn = 'pwpd_cert_v1.0.zip'):
#    exec_dir = os.path.expanduser(exec_dir)
#    
#    zip_f = zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED)
#    for dirpath, dirnames, filenames in os.walk(exec_dir):
#        for fn in filenames:
#            zip_f.write(os.path.join(dirpath,fn), fn, zipfile.ZIP_DEFLATED)
#        if len(filenames) == 0:
#            f = zipfile.ZipInfo(dirpath + '/')
#            zip_f.writestr(f, "")
#            
#    zip_f.close()
    out_dir = exec_dir = os.path.expanduser(exec_dir)
    
    if exec_dir.endswith(os.sep):
        out_dir = os.path.split(exec_dir[:-1])[0]
        exec_dir = os.path.split(exec_dir[:-1])[1]
    else:
        out_dir = os.path.split(exec_dir)[0]
        exec_dir = os.path.split(exec_dir)[1]   
    out_fn = out_dir + '/' + out_fn
    
    cmd = 'zip -r ' + out_fn + ' ' + exec_dir
    _exec_cmd(cmd)
    
    print >> sys.stdout, cmd + '  SUCCESSED.'
    
def _unzip_exec(exec_zip, target_dir = ''):
    exec_zip = os.path.expanduser(exec_zip)
    
    # default extract target directory.
    if not target_dir:
        target_dir = os.path.splitext(exec_zip)[0]
    
    zip_f = zipfile.ZipFile(exec_zip, 'r')
    for k in zip_f.infolist():
        save_path = os.path.join(target_dir, k.filename)
        save_dir = os.path.dirname(save_path)
        # empty directory in archive.
        if save_path.endswith(os.sep):
            if not os.path.exists(save_path):
                os.makedirs(save_path)
        # general file in archive.
        else:
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            #
            f = open(save_path, 'wb')
            f.write(zip_f.read(k))
            f.close()
    #
    zip_f.close()


def _do_opt():
    from optparse import OptionParser
    
    usage = ''' Client util for VPRP (Virtual Public Resource Platform). \n
    usage: %prog -s [-f input][-l LINES] {-p PREFIX} 
           %prog -z [-d dir] {-o output zip file}
           %prog -u [-f input zip file] [-d target directory]
    '''
    parser = OptionParser(usage)
    #
    parser.add_option('-s', '--split', dest = 'split',
                      action = 'store_true', default = False,
                      help = 'Split raw input data.')
    parser.add_option('-z', '--zip', dest = 'zip',
                      action = 'store_true', default = False,
                      help = 'Zip the execution files.')
    parser.add_option('-u', '--unzip', dest = 'unzip',
                      action = 'store_true', default = False,
                      help = 'Unzip the execution file.')
    
    parser.add_option('-f', '--file', dest = 'file',
                      action = 'store', default = '',
                      help = 'Input file name.')
    parser.add_option('-p', '--prefix', dest = 'prefix',
#                       action = 'store', default = time.strftime('split_%Y%m%d_', time.localtime()),
                      action = 'store', default = '',
                      help = 'Prefix name of out files.')
    parser.add_option('-l', '--line', type = 'int', dest = 'lines',
                      action = 'store', default = 5000,
                      help = 'Line num. of each output file.')
    
    parser.add_option('-d', '--dir', dest = 'dir',
                      action = 'store', default = '',
                      help = 'Execution directory path.')
    parser.add_option('-o', '--out', dest = 'out',
                      action = 'store', default = '',
                      help = 'Output zip file name.')
    #
    (opts, args) = parser.parse_args()
    return opts, args

def _do_main(opts, args):
    
    if opts.split:
        _split_input(opts.file, opts.prefix, opts.lines)
    elif opts.zip:
        _zip_exec(opts.dir)
    elif opts.unzip:
        _unzip_exec(opts.file, opts.dir)

if __name__ == '__main__':
    opts, args = _do_opt()
    _do_main(opts, args)

